import { FC, useCallback, useEffect, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import styles from "./index.module.scss";
import DOMPurify from "dompurify";
import highlight from "highlight.js";
import "highlight.js/styles/github.css";
import ContentLoader from "react-content-loader";
import { getArticleById } from "@/store/actions/article";
import { useInitialState } from "@/utils/use-initial-state";
import throttle from "lodash/throttle"; //调用lodash中的节流函数
import Back from "@/shared/back";
import Header from "@/shared/header";
import { MoreOutline } from "antd-mobile-icons";
import dayjs from "dayjs";
import { InfiniteScroll } from "antd-mobile";
interface ArticleProps {}
// 导航栏高度的常量
const NAV_BAR_HEIGTH = 45;
const Article: FC<ArticleProps> = () => {
  const location = useLocation();
  // console.log(location);
  const pathname = location.pathname;

  // 使用split方法将pathname字符串按'/'分割成数组
  const pathArray = pathname.split("/");

  // 获取文章ID，假设文章ID在数组的最后一个元素
  const artId = pathArray[pathArray.length - 1];

  //console.log(artId); // 输出
  // 获取文章详情
  const { detail } = useInitialState(
    () => getArticleById(artId ?? ""),
    "article"
  );

  // 解构出文章详情数据
  const {
    // art_id,
    // aut_id,
    // attitude,
    // is_collected,
    content,
    // is_followed,
    // aut_name,
    // aut_photo,
    // comm_count,
    // like_count,
    // pubdate,
    // read_count,
    // title,
  } = detail ?? {};

  // 文章详情代码内容高亮
  useEffect(() => {
    const dgHtmlDOM = document.querySelector(".dg-html");
    const codes = dgHtmlDOM?.querySelectorAll<HTMLElement>("pre code");

    if (codes && codes.length > 0) {
      codes.forEach((el) => {
        highlight.highlightElement(el);
      });
      return;
    }

    highlight.configure({
      // 忽略警告
      ignoreUnescapedHTML: true,
    });
    // 直接找到所有的 pre 标签
    const pres = dgHtmlDOM?.querySelectorAll("pre");
    if (pres && pres.length > 0) {
      pres.forEach((el) => {
        // 让每个 code 内容实现代码高亮
        highlight.highlightElement(el);
      });
    }
  }, [detail]);

  const [loading, setLoading] = useState(true);
  useEffect(() => {
    if (detail) {
      setLoading(false);
    }
  }, [detail]);

  //导航栏中展示作者信息
  const wrapperRef = useRef<HTMLDivElement>(null);
  const authorRef = useRef<HTMLDivElement>(null);
  const [showNavAuthor, setShowNavAuthor] = useState(false);

  // 导航栏中展示作者信息
  useEffect(() => {
    if (loading) return;

    const wrapperDOM = wrapperRef.current!;

    // 创建一个节流函数
    const handleScroll = throttle(() => {
      const { bottom } = authorRef.current!.getBoundingClientRect();
      // 44 是 NavBar 的高度，因为 NavBar 会挡住页面内容，所以，此处需要减去它的高度
      if (bottom - 44 <= 0) {
        setShowNavAuthor(true);
      } else {
        setShowNavAuthor(false);
      }
    }, 1000);

    wrapperDOM.addEventListener("scroll", handleScroll);
    return () => wrapperDOM.removeEventListener("scroll", handleScroll);
  }, [loading]);

  // 用于存储评论区域的元素对象
  const commentRef = useRef<HTMLDivElement | null>(null);
  //点击滚动到评论内容位置
  // 数量偏移量
  const [offset, setOffset] = useState<string | undefined>();
  // 是否还有更多数据可以加载
  const [hasMore, setHasMore] = useState(true);
  // 用于获取评论列表的方法
  //   const [requestComments, { data: commentsResponse }] =
  //     useLazyRequestCommentsQuery();
  //   // 获取本地存储的评论列表
  //   const comments = useTypedSelector(commentsSelectors.selectAll);
  //   const dispatch = useTypedDispatch();
  // 用于加载更多数据
  //   const loadMore = () => {
  //     return requestComments({ type: "a", source: id!, offset, limit: 10 })
  //       .unwrap()
  //       .then(function (response) {
  //         // 保存评论列表
  //         dispatch(saveComments(response.data.results));
  //         // 设置获取数据的偏移量
  //         setOffset(response.data.last_id);
  //         // 设置是否还有更多数据可以加载
  //         setHasMore(response.data.last_id !== response.data.end_id);
  //       });
  //   };
  // 重置评论列表
  //   const resetComments = useCallback(() => {
  //     setOffset(undefined);
  //     setHasMore(true);
  //     dispatch(clearComments());
  //   }, [dispatch]);

  //骨架屏
  if (loading) {
    return (
      <ContentLoader
        speed={2}
        width={375}
        height={230}
        viewBox="0 0 375 230"
        backgroundColor="#f3f3f3"
        foregroundColor="#ecebeb"
      >
        <rect x="16" y="8" rx="3" ry="3" width="340" height="10" />
        <rect x="16" y="26" rx="0" ry="0" width="70" height="6" />
        <rect x="96" y="26" rx="0" ry="0" width="50" height="6" />
        <rect x="156" y="26" rx="0" ry="0" width="50" height="6" />
        <circle cx="33" cy="69" r="17" />
        <rect x="60" y="65" rx="0" ry="0" width="45" height="6" />
        <rect x="304" y="65" rx="0" ry="0" width="52" height="6" />
        <rect x="16" y="114" rx="0" ry="0" width="340" height="15" />
        <rect x="263" y="208" rx="0" ry="0" width="94" height="19" />
        <rect x="16" y="141" rx="0" ry="0" width="340" height="15" />
        <rect x="16" y="166" rx="0" ry="0" width="340" height="15" />
      </ContentLoader>
    );
  }

  return (
    <>
      {/* 顶部固定部分 */}
      <div className={styles.header}>
        <Header
          title={
            showNavAuthor && <div className="nav-author">阿斯顿发斯诺克那</div>
          }
          left={<Back />}
          right={<MoreOutline />}
        />
      </div>
      {/* 内容部分 */}
      <div className={styles.article} ref={wrapperRef}>
        <div className={styles.title}>{detail?.title}</div>
        <div className={styles.meta}>
          <span>{dayjs(detail?.pubdate).locale("zh-cn").format("LL")}</span>
          <span>{detail?.read_count} 阅读</span>
          <span>{detail?.comm_count} 评论</span>
        </div>
        <div className={styles.author} ref={authorRef}>
          <div className={styles.avatar}>
            <img src={detail?.aut_photo} alt="" />
            <span>{detail?.aut_name}</span>
            <button>关注</button>
          </div>
        </div>
        <div className={styles.content}>
          <div
            className="content-html dg-html"
            dangerouslySetInnerHTML={{
              __html: DOMPurify.sanitize(content),
            }}
          />
        </div>
        <div className={styles.comment} ref={commentRef}>
          {/* <h4 className={styles.title}>
            全部评论 ({commentsResponse?.data.total_count})
          </h4>
          {commentsResponse?.data.results.length === 0 && (
            <div className={styles.noReply}>
              <img src={require("@images/none.png")} alt="" />
              <span>还没有人评论哦</span>
            </div>
          )}
          {comments.map((comment) => (
            <Comment key={comment.com_id} comment={comment} />
          ))} */}
          {/* 使用 InfiniteScroll 组件实现无限滚动加载更多数据 */}
          {/* <InfiniteScroll hasMore={hasMore} loadMore={loadMore} /> */}
        </div>
      </div>
    </>
  );
};
export default Article;